package com.cwj.algorithm.linear;

import com.cwj.exception.NotationException;

import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;

/**
 * 逆波兰表达式求职
 * @author chenwujie
 * @date 2020/11/1615:34
 */
public class ReversePolishNotation {

    public static int calculate(String[] notation){
        Deque<Integer> stack = new LinkedList<>();
        for (String s : notation) {
            if (isValue(s)) {
                stack.push(Integer.valueOf(s));
            } else {
                Integer v2 = stack.pop();
                Integer v1 = stack.pop();
                Integer v3 = arithmetic(v1, v2, s);
                stack.push(v3);
            }
        }
        if(stack.size() != 1){
            throw new NotationException("notation: " + Arrays.toString(notation) + "格式不正确");
        }
        return stack.pop();
    }

    private static Integer arithmetic(Integer v1, Integer v2, String s) {
        Integer v3 = null;
        switch(s){
            case "+":
                v3 = v1 + v2;
                break;
            case "-":
                v3 = v1 - v2;
                break;
            case "*":
                v3 = v1 * v2;
                break;
            case "/":
                v3 = v1 / v2;
                break;
            default:
                break;
        }

        return v3;
    }

    private static boolean isValue(String s) {
            return s.matches("\\d+");
    }
}
